<template>
  <div id="creatOrder">
    <img :src="detail.goodsImage" alt="" class="shopImg" />
    <div class="price">
      <div class="left">优惠后金额：</div>
      <div class="right">{{ detail.salePrice }}元</div>
    </div>
    <div class="backIndex" @click="goWxPay">立即支付</div>
    <img :src="detail.goodsDetailsImage" alt="" class="notice" />
  </div>
</template>

<script>
import req from "@/utils/index";
import { hostName, apiServer } from "@/utils/config";
import { Toast, Dialog } from "vant";
import InApp from "detect-inapp";
const inapp = new InApp(navigator.userAgent || navigator.vendor);
export default {
  data() {
    return {
      orderNo: "",
      goodsNo: "",
      payModeList: {},
      weixinAuthInfo: {},
      didPay: "",
      content: "",
      detail: {},
      isGsq: false,
    };
  },
  methods: {
    creatOrderNum(id) {
      let data = {
        channelNo: window.localStorage.getItem("channelNo"),
        goodsNo: this.goodsNo || window.localStorage.getItem("goodsNo"),
        payModeCode: this.payModeList.payModeCode,
      };
      req(
        "get",
        `/goods/order/create?channelNo=${data.channelNo}&goodsNo=${data.goodsNo}&payModeCode=${data.payModeCode}`,
        {}
      ).then((res) => {
        if (res.rspCode == "000000") {
          this.orderNo = res.data.orderNo;
          window.localStorage.setItem("orderNum", res.data.orderNo);
          if (id == 1) {
            this.handleWXPay(
              this.content,
              window.localStorage.getItem(this.goodsNo),
              this.$route.path
            );
          } else {
            this.handleWeiXinPay(this.orderNo);
          }
        }
      });
    },
    // 微信支付 JSAPI
    async handleWXPay(content, goodsNo, path) {
      const contentData = JSON.parse(content);
      if (contentData.rspCode !== "000000") {
        this.$router.replace({
          name,
          params: {
            goodsNo: goodsNo,
            didPay: "noYet",
          },
        });
        return;
      }
      Toast.loading("正在调起微信支付");
      let res;
      let orderNo;
      // const url = `/creatOrder?goodsNo=ZG210507PpZyrRZA&didPay=noYet`;
      const url = `/creatOrder`;
      const callbackUrl = `${hostName}${url.replace("noYet", "paid")}`;
      req("post", `/wxpay/qy/pay`, {
        callbackUrl,
        orderNo: window.localStorage.getItem("orderNum"),
        sceneInfo: "JSAPI",
        openId: contentData.data,
        tradeType: "JSAPI",
      }).then((result) => {
        if (result.rspCode == "000000") {
          this.weixinAuthInfo = result.data;
          this.onBridgeReady();
        }
      });
    },
    // 微信支付 H5
    async handleWeiXinPay(orderNo) {
      const token = window.localStorage.getItem("token");
      // const callbackUrl = `${hostName}${this.$route.path}?goodsNo=ZG210507PpZyrRZA&didPay=paid`;
      const callbackUrl = `${hostName}${this.$route.path}`;
      let sceneInfo;
      if (inapp.isInApp) {
        if (inapp.ua.includes("Android")) {
          sceneInfo =
            '{"h5_info": {"type":"Android","app_name": "擎天助车主版","package_name": "com.tmbj.client"}}'; // android
        } else {
          sceneInfo =
            '{"h5_info": {"type":"IOS","app_name": "擎天助","bundle_id": "com.tmbj.qtzUser"}}'; // ios
        }
      } else {
        sceneInfo = `{"h5_info": {"type":"Wap","wap_url": "${callbackUrl}","wap_name": "同升优创"}}`; // web
      }
      req("post", `/wxpay/qy/pay`, {
        callbackUrl,
        orderNo: orderNo || window.localStorage.getItem("orderNum"),
        sceneInfo,
        tradeType: "MWEB",
      }).then((result) => {
        if (result.data && result.data.tradeNo && result.data.webUrl) {
          const { tradeNo, webUrl } = result.data;
          if (typeof tradeNo === "string") {
            window.localStorage.setItem("tradeNo", tradeNo);
          }
        }
      });
    },
    // 吊起微信支付
    onBridgeReady() {
      const _this = this;
      const weixinAuthInfo = this.weixinAuthInfo;
      WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          appId: weixinAuthInfo.appId, //公众号名称，由商户传入
          timeStamp: weixinAuthInfo.timeStamp, //时间戳，自1970年以来的秒数
          nonceStr: weixinAuthInfo.nonceStr, //随机串
          package: weixinAuthInfo.package_rname,
          signType: weixinAuthInfo.signType, //微信签名方式：
          paySign: weixinAuthInfo.paySign, //微信签名
        },
        (res) => {
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            // 使用以上方式判断前端返回,微信团队郑重提示：
            //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
            if (window.localStorage.getItem("whatBuy") == "vip") {
              this.$router.push({
                name: "vipBuy",
              });
            } else if (window.localStorage.getItem("whatBuy") == "gsqVip") {
              this.$router.push({
                name: "waterVip",
              });
            } else {
              this.$router.push({
                name: "water",
              });
            }
          }
        }
      );
    },
    // 点击确定继续支付
    goWxPay() {
      // const url = `/creatOrder?goodsNo=ZG210507PpZyrRZA&didPay=noYet`;
      const userMsg = JSON.parse(window.localStorage.getItem("userMsg"));
      if (
        !window.localStorage.getItem("logintoken") ||
        !window.localStorage.getItem("phone")
      ) {
        this.$router.push({
          name: "getUser",
          query: {
            spid: this.goodsNo,
          },
        });
        return;
      }
      if (
        userMsg.userType == 0 &&
        window.localStorage.getItem("geSangQuanGoodsNo") == this.goodsNo
      ) {
        Dialog.confirm({
          message: "您的手机号还不是平台的会员， 是否要成为会员？",
        })
          .then(() => {
            // on confirm
            window.localStorage.setItem("whatBuy", "gsqVip");
            // window.location.href = `http://localhost:8080/creatOrder?goodsNo=${window.localStorage.getItem("VipGoodsNo")}&didPay=noYet`
            window.location.href =
              hostName +
              `/creatOrder?goodsNo=${window.localStorage.getItem(
                "VipGoodsNo"
              )}&didPay=noYet`;
            // this.$router.push({
            //   name: "creatOrder",
            //   query: {
            //     goodsNo: window.localStorage.getItem("VipGoodsNo"),
            //     didPay: "noYet",
            //   },
            // });
          })
          .catch(() => {
            // on cancel
          });
        return;
      }
      const url = `/creatOrder`;
      // const url = `/creatOrder/${window.localStorage.getItem('goodsNo')}/noYet`;
      if (this.payModeList.payModeCode === "TSYCWX") {
        if (inapp.isInApp && inapp.browser === "wechat") {
          if (!apiServer || !hostName || !this.$route.path) {
            return;
          }
          window.location.href = `${apiServer}/wx/auth/qy/redirectUri?callbackUrl=${encodeURIComponent(
            hostName + url
          )}`;
          return;
        }
      }
      this.creatOrderNum();
    },
  },
  created() {
    if (this.$route.query.goodsNo) {
      this.goodsNo = this.$route.query.goodsNo;
      this.didPay = this.$route.query.didPay;
      window.localStorage.setItem("didPay", this.$route.query.didPay);
      window.localStorage.setItem("goodsNo", this.goodsNo);
    }
    req(
      "get",
      `/qyHome/list/detail?goodsNo=${window.localStorage.getItem("goodsNo")}`,
      {}
    ).then((res) => {
      if (res.rspCode == "000000") {
        this.detail = res.data;
      }
    });
    if (this.$route.query.isGsq) {
      this.isGsq = this.$route.query.isGsq;
    }
    if (
      this.$route.query.goodsNo == window.localStorage.getItem("VipGoodsNo")
    ) {
      window.localStorage.setItem("whatGood", "vip");
    } else if (
      this.$route.query.goodsNo ==
      window.localStorage.getItem("geSangQuanGoodsNo")
    ) {
      window.localStorage.setItem("whatGood", "geSangQuan");
    }
    this.payModeList = JSON.parse(window.localStorage.getItem("payModeList"));
    // 微信支付相关
    const { name, path } = this.$route;
    const didPay = this.$route.params.didPay;
    const goodsNo = this.$route.params.goodsNo;
    const content = (this.content = this.$route.query.content || "");
    const callbackData = this.$route.query.callbackData || "";
    if (didPay && didPay === "paid") {
    } else if (content && typeof content === "string") {
      this.creatOrderNum(1);
    }
    req("get", `/qy/user/info`, {}).then((res) => {
      if (res.rspCode == "000000") {
        window.localStorage.setItem("userMsg", JSON.stringify(res.data));
        if (res.data.userType == 0) {
          this.$store.state.isright = false;
        } else {
          this.$store.state.isright = true;
        }
      } else {
        this.$store.state.isright = false;
      }
    });
  },
};
</script>

<style lang='scss' scoped>
#creatOrder {
  text-align: center;
  padding-top: 0.5rem;
}
.shopImg {
  width: 90%;
  height: 5rem;
}
.price {
  overflow: hidden;
  width: 70%;
  font-size: 0.5rem;
  font-weight: 700;
  margin: 1rem auto 0.5rem;
  .left {
    float: left;
  }
  .right {
    float: right;
    color: #c01d32;
  }
}

.backIndex {
  display: inline-block;
  box-sizing: border-box;
  width: 70%;
  box-sizing: border-box;
  padding: 0.3rem 2.5rem;
  border: 1px solid #c41e34;
  color: #c41e34;
  border-radius: 1rem;
  font-weight: 700;
  font-size: 0.4rem;
}
.notice {
  width: 90%;
  margin-top: 1rem;
}
</style>